<script setup lang="ts">
defineOptions({
  name: "add"
});

import { ref, reactive, computed, onMounted } from "vue";
import type { FormInstance, FormRules } from "px-ui";
import { createFillingManage, updateFillingManage, queryFillingManageDetail, getFillingWagonMaterialOptions } from "@/api/modules/operation";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";

interface Props {
  // 弹框类型 add 新增   edit 编辑
  type: "add" | "edit";
  id: string;
}

const props = withDefaults(defineProps<Props>(), {});
const dialogTableVisible = defineModel({ type: Boolean, default: false });
const title = computed(() => (props.type === "add" ? "新增" : "编辑"));

interface RuleForm {
  transportDate: string;
  material: string;
  capacity: string;
  supplier: string;
  tankTruckNo: string;
  lotNumber: string;
  dutyEngineer: string;
  supplierEngineer: string;
  remark: string;
}

const materialOptions = ref<Array<any>>([]);
const loading = ref<boolean>(false);
const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  transportDate: "",
  material: "",
  capacity: undefined,
  supplier: "",
  tankTruckNo: "",
  lotNumber: "",
  dutyEngineer: "",
  supplierEngineer: "",
  remark: ""
});

const rules = reactive<FormRules<RuleForm>>({
  transportDate: [{ required: true, message: "请选择载送日期", trigger: "blur" }],
  material: [{ required: true, message: "请输入载送物质", trigger: "blur" }],
  capacity: [{ required: true, message: "请输入载送数量", trigger: "blur" }],
  supplier: [{ required: true, message: "请输入供应厂商", trigger: "blur" }],
  tankTruckNo: [{ required: true, message: "请输入槽车车号", trigger: "blur" }],
  lotNumber: [{ required: true, message: "请输入Lot Number", trigger: "blur" }],
  dutyEngineer: [{ required: true, message: "请输入值班工程师", trigger: "blur" }],
  supplierEngineer: [{ required: true, message: "请输入厂商工程师", trigger: "blur" }],
  remark: [{ required: false, message: "请输入备注", trigger: "blur" }]
});

const emits = defineEmits(["submit"]);

const cancelHandler = () => {
  dialogTableVisible.value = false;
};

const submitHandler = useThrottleFn(async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true;
      const { id } = props;
      const params = { ...ruleForm };
      if (props.type === "add") {
        await createFillingManage(params, () => {
          loading.value = false;
        });
      } else if (props.type === "edit") {
        params["id"] = id;
        await updateFillingManage(params, () => {
          loading.value = false;
        });
      }
      loading.value = false;
      emits("submit");
      dialogTableVisible.value = false;
    } else {
      console.error("error submit!", fields);
    }
  });
}, delay);

const initOptions = async () => {
  const res = await getFillingWagonMaterialOptions();
  materialOptions.value = res?.map(({ code: value = "", name: label = "" }) => ({ value, label }));
};

const init = async () => {
  if (props.type === "edit") {
    const { id } = props;
    loading.value = true;
    const res = await queryFillingManageDetail(id, () => {
      loading.value = false;
    });
    const {
      transportDate = "",
      material = "",
      capacity = "",
      supplier = "",
      tankTruckNo = "",
      lotNumber = "",
      dutyEngineer = "",
      supplierEngineer = "",
      remark = ""
    } = res;
    ruleForm.transportDate = transportDate;
    ruleForm.material = material;
    ruleForm.capacity = capacity;
    ruleForm.supplier = supplier;
    ruleForm.tankTruckNo = tankTruckNo;
    ruleForm.lotNumber = lotNumber;
    ruleForm.dutyEngineer = dutyEngineer;
    ruleForm.supplierEngineer = supplierEngineer;
    ruleForm.remark = remark;
    loading.value = false;
  }
};

onMounted(async () => {
  await initOptions();
  await init();
});
</script>

<template>
  <px-dialog v-model="dialogTableVisible" :title="title" width="1000px">
    <px-form
      ref="ruleFormRef"
      v-loading="loading"
      :model="ruleForm"
      :rules="rules"
      inline
      label-width="100px"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <px-row :gutter="32">
        <px-col :span="12">
          <px-form-item label="载送日期" prop="transportDate">
            <px-date-picker
              v-model="ruleForm.transportDate"
              clearable
              type="date"
              :editable="false"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :default-time="new Date(2000, 1, 1)"
              placeholder="请选择载送日期"
            />
          </px-form-item>
        </px-col>

        <px-col :span="12">
          <px-form-item label="载送物质" prop="material">
            <px-select v-model="ruleForm.material" clearable filterable placeholder="请选择载送物质">
              <px-option v-for="item in materialOptions" :key="item.value" :label="item.label" :value="item.value" />
            </px-select>
          </px-form-item>
        </px-col>

        <px-col :span="12">
          <px-form-item label="载送数量" prop="capacity">
            <px-input
              v-model.trim.number="ruleForm.capacity"
              class="px-input-number-no-controls"
              type="number"
              clearable
              :min="0"
              placeholder="请输入载送数量"
            />
          </px-form-item>
        </px-col>

        <px-col :span="12">
          <px-form-item label="供应厂商" prop="supplier">
            <px-input v-model.trim="ruleForm.supplier" clearable placeholder="请输入供应厂商" />
          </px-form-item>
        </px-col>

        <px-col :span="12">
          <px-form-item label="槽车车号" prop="tankTruckNo">
            <px-input v-model.trim="ruleForm.tankTruckNo" clearable placeholder="请输入槽车车号" />
          </px-form-item>
        </px-col>

        <px-col :span="12">
          <px-form-item label="Lot Number" prop="lotNumber">
            <px-input v-model.trim="ruleForm.lotNumber" clearable placeholder="请输入Lot Number" />
          </px-form-item>
        </px-col>

        <px-col :span="12">
          <px-form-item label="值班工程师" prop="dutyEngineer">
            <px-input v-model.trim="ruleForm.dutyEngineer" clearable placeholder="请输入值班工程师" />
          </px-form-item>
        </px-col>

        <px-col :span="12">
          <px-form-item label="厂商工程师" prop="supplierEngineer">
            <px-input v-model.trim="ruleForm.supplierEngineer" clearable placeholder="请输入厂商工程师" />
          </px-form-item>
        </px-col>

        <px-col :span="24">
          <px-form-item label="备注" prop="remark">
            <px-input v-model.trim="ruleForm.remark" clearable type="textarea" maxlength="200" show-word-limit placeholder="请输入备注" />
          </px-form-item>
        </px-col>
      </px-row>
    </px-form>

    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancelHandler">取消</px-button>
        <px-button type="primary" :loading="loading" @click="submitHandler"> 确认 </px-button>
      </span>
    </template>
  </px-dialog>
</template>

<style lang="scss" scoped>
:deep(.px-form-item) {
  width: 100%;

  .px-form-item__content {
    .px-input-number .px-input__inner {
      text-align: left;
    }

    .px-input,
    .px-input-number,
    .px-select,
    .px-date-picker,
    .px-time-picker,
    .px-tree-select {
      width: 100%;
    }
  }
}
</style>
